
#python3
import os
import re
import sys
import xlwt
from xlwt import Style

pattern = r"^\[(.{12}).*\[6011:登录\]\[(.+):(.+):(.+)\]\[(\d{2,32})\].*应答数据"


#返回解析出来的登录信息
def parse_one_line(line : str):
    if len(line) == 0:
        return {}
    
    result = re.search(pattern,line)
    if not result:
        return {}
    
    log_time = result.groups()[0]
    log_ip = result.groups()[1]
    log_mac = result.groups()[2]
    log_hd = result.groups()[3]
    log_acc = result.groups()[4]

    return {"time":log_time,
            "ip":log_ip,
            "mac":log_mac,
            "hd":log_hd,
            "account":log_acc}


#将单个文件的记录，存放在list中
#返回内容格式为 
def parse_one_log(filename:str):
    records = []
    print("日志路径:",work_path)
    filpath = os.path.join(work_path, filename)
    with open(file=filpath, mode='r',errors='ignore') as logfile:
        while True:
            line = logfile.readline()
            if not line:
                break
            
            login_info = parse_one_line(line)
            if len(login_info) == 0:
                continue
            
            records.append(login_info)
    print("日志文件%s解析完成"%filename)
    return records

def format_time(time:str):
    time_str = ""
    for elem in time.split(':'):
        time_str += elem

    return time_str   

def format_mac(mac:str):
    if len(mac) != 12:
        return mac
    mac_str = []
    for i in range(len(mac)):
        if i%2 == 0:
            mac_str.append(mac[i:i+2])
    
    return '-'.join(mac_str)


def write_one_log(worksheet, logfile:str, start_rec_index:int):
    #向sheet写入数据    
    records = parse_one_log(logfile)
    for i in range(len(records)):
        curr_index = i + start_rec_index
        worksheet.write(curr_index,0,records[i]["account"])
        worksheet.write(curr_index,1,logfile.split('.')[0])
        new_time = format_time(records[i]["time"])
        worksheet.write(curr_index,2,new_time)

        worksheet.write(curr_index,3,records[i]["ip"])

        new_mac = format_mac(records[i]["mac"])
        worksheet.write(curr_index,4,new_mac)

        worksheet.write(curr_index,5,records[i]["hd"])

    return len(records)

def get_files(path:str, start:int, end:int):
    dir_list = os.listdir(path)

    files = []
    for file in dir_list:
        file_suffix = os.path.splitext(file)[1]
        if file_suffix != ".log":
            continue

        file_name = os.path.splitext(file)[0]
        if len(file_name) != 8:
          continue
        
        if start == 0:
            files.append(file)
        elif int(file_name) >= start and int(file_name)<=end:
            files.append(file)

    return files

def prepare_wroksheet(worksheet):
    title = ['资金账户','日期','时间','IP','Mac','硬盘序列号']

    #设置表头格式
    style = xlwt.XFStyle()
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    #设置背景色
    pattern.pattern_fore_colour = 3
    style.pattern = pattern

    #写入表头
    for i in range(len(title)) :
        worksheet.col(i).width = 256*20
        worksheet.write(0,i,title[i],style)

     
'''
可选入参
param 1 : 起始日期
param 2 : 结束日期
param 3 : 文件路径
'''        
if __name__ == '__main__':
    global work_path
    work_path = "./"
    start = 0
    end = 0
    
    if len(sys.argv) >= 3:
        start = int(sys.argv[1])
        end = int(sys.argv[2])
        if len(sys.argv) == 4:
            work_path = str(sys.argv[3])

    print("输入参数为:", start, end, work_path)
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet("登录流水")
   
    prepare_wroksheet(worksheet)

    files = get_files(work_path, start, end)
    print("需要解析的日志文件: \n", files)

    cur_rec_index = 1
    for file in files:
        cur_rec_index += write_one_log(worksheet, file, cur_rec_index)

    workbook.save("./登录流水.xls")

